﻿using Agvlaser.Sqlite;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using static Agvlaser.DataStructClass;

namespace Agvlaser
{
    /// <summary>
    /// SelectRouteWindow.xaml 的交互逻辑
    /// </summary>
    public partial class SelectRouteWindow : Window
    {
        int routeNum;
        public SelectRouteWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //加载当前路径信息
            tbRouteNum.Text = GlobalVar.routeInfo.RouteNum.ToString();
            tbRouteDes.Text = GlobalVar.routeInfo.RouteDes.ToString();
        }
        bool viald = false;
        private void tbRouteNum_TextChanged(object sender, TextChangedEventArgs e)
        {
            //判断路径号是否为数字
            if (IsNumber(tbRouteNum.Text))
            {
                routeNum = int.Parse(tbRouteNum.Text);
                //读取路径信息
                SqliteHelper sql = new SqliteHelper();
                string str = sql.ExecuteScalar(string.Format("select route from route where num={0}", routeNum)) as string;
                //存在，提示进行修改
                if (str != null)
                {
                    viald = true;
                    //更新界面描述信息
                    Route route = JsonConvert.DeserializeObject<Route>(str);
                    tbRouteDes.Text = route.RouteDes;
                    tbRouteNum.Background = Brushes.White;
                }
                else
                {
                    viald = false;
                    tbRouteNum.Background = Brushes.Red;
                    tbRouteDes.Text = "";
                }
            }
        }
        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Submit_Click(object sender, RoutedEventArgs e)
        {
            if (viald)
            {
                //更新当前路径
                GlobalVar.systemConfig.RouteConfig.RouteNow = routeNum;
                //存储
                SqliteHelper sql = new SqliteHelper();
                //存储数据
                string str = JsonConvert.SerializeObject(GlobalVar.systemConfig, Formatting.Indented);
                //存储
                int res = sql.ExecuteNonQuery(string.Format("update config set value='{0}' where key='{1}'", str, "system"));
                if (res <= 0)
                    MessageBox.Show("存储配置失败！");
                this.Close();
            }
            else
            {
                MessageBox.Show("目标路径不存在，请先创建！");
            }
        }
        /// <summary>
        /// 判断字符串是否是数字
        /// </summary>
        public static bool IsNumber(string s)
        {
            if (string.IsNullOrWhiteSpace(s)) return false;
            const string pattern = "^[0-9]*$";
            Regex rx = new Regex(pattern);
            return rx.IsMatch(s);
        }
    }
}
